"""
@author: yinjx
@file: user.py
@time: 2023/8/3 19:36
"""
from . import user_bp
from flask import request
from flask_restful import Resource, Api
from models.user import User
from libs.response import generate_response
from forms.user import UserForm, LoginForm
from libs.auth import create_token
from libs.handler import default_error_handler

api = Api(user_bp)

#异常标准化返回
#handle_error 原本处理异常情况返回的一个方法
#当发生异常情况时，会自动调用handle_error函数处理异常返回
#api.handle_error = default_error_handler

class UserRegister(Resource):
    # #做了数据校验版本
    def  post(self):
        #try:
            data = request.json
            form = UserForm(data = data)
            if form.validate():
                User.create_user(
                    username= data.get("username"),
                    password = form.password.data)
                return generate_response(message="注册成功",code=0)
            else:
                return generate_response(code=1, message=form.errors)
        #except:
           #return generate_response(code=1, message="注册失败!")

    # 不做数据校验
    # def post(self):
    #     username = request.json.get("username")
    #     password = request.json.get("password")
    #     if username is not None:
    #         if password is not None:
    #             User.create_user(username,password)
    #             return generate_response(message="register success", code=10000)
    #         else:
    #             return generate_response(message="no password", code=10001)
    #     else:
    #         return generate_response(message="no username", code=10002)

api.add_resource(UserRegister,"/user")

#登录视图
class LoginView(Resource):
    def post(self):
        data = request.json
        form = LoginForm(data = data)
        user = form.validate()
        if user:
            #验证通过，生成token
            token = create_token(user.id)
            return generate_response(message="login success", code=0, data={"token":token,
                                                                            "username":user.username})
        else:
            return generate_response(message="login fail", code=1)

api.add_resource(LoginView, "/login")